package com.fc.mall.service.impl;

import com.fc.mall.dto.OmsBargainDto;
import com.fc.mall.dto.OmsBargainParam;
import com.fc.mall.mapper.OmsBargainListMapper;
import com.fc.mall.mapper.OmsBargainMapper;
import com.fc.mall.model.OmsBargain;
import com.fc.mall.model.OmsBargainExample;
import com.fc.mall.model.OmsBargainList;
import com.fc.mall.model.OmsBargainListExample;
import com.fc.mall.service.OmsBargainService;
import com.fc.mall.util.DateTimeHelper;
import com.fc.mall.util.Utils;
import com.github.pagehelper.PageHelper;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by sunny on 2019/9/25.
 */
@Service
public class OmsBargainServiceImpl implements OmsBargainService {

    @Autowired
    private OmsBargainMapper bargainMapper;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private OmsBargainListMapper bargainListMapper;

    @Override
    public List<OmsBargainDto> getList(OmsBargainParam bargainParam, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        OmsBargainDto omsBargainDto = new OmsBargainDto();
        OmsBargainExample bargainExample = new OmsBargainExample();
        OmsBargainExample.Criteria criteria = bargainExample.createCriteria().andProductBargainIdEqualTo(bargainParam.getBargainProdId());
        if(!StringUtils.isEmpty(bargainParam.getNickname()))
        {
            criteria.andNicknameLike(Utils.urlEncoderTransfer(bargainParam.getNickname()));
        }

        List<OmsBargain> bargainList = bargainMapper.selectByExample(bargainExample);
        List<OmsBargainDto> omsBargainDtoList = mapperFacade.mapAsList(bargainList, OmsBargainDto.class);

        omsBargainDtoList.stream().forEach(dto -> {
            OmsBargainListExample listExample = new OmsBargainListExample();
            listExample.createCriteria().andBargainIdEqualTo(dto.getId().intValue());
            List<OmsBargainList> assistorList = bargainListMapper.selectByExample(listExample);
            assistorList.stream().forEach(v -> {
                v.setNickname(Utils.urlDecoderTransfer(v.getNickname()));
            });
            dto.setNickname(Utils.urlDecoderTransfer(dto.getNickname()));
            dto.setAssistorList(assistorList);
            dto.setAssistorCount(assistorList.size());

            if(DateTimeHelper.getCurrentDateFromZero().after(dto.getExpiredTime())
                    || dto.getOrderId() != null)
            {
                dto.setStatus(1);
            }
            else
            {
                dto.setStatus(0);
            }
        });

        return omsBargainDtoList;
    }
}
